package com.sk.waste.app.views;

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.WindowManager
import android.widget.Button
import android.widget.LinearLayout.LayoutParams
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.adapters.DistrictAdapter
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.DistrictModel
import com.sk.waste.app.models.TypeModel
import com.sk.waste.app.utils.OkHttpUtil
import okhttp3.Call
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException


/**
 *  @time 2025/5/14  9:07
 *  @desc 政区
 */
class DistrictPopuWindow() : PopupWindow(), OnClickListener {

    private val TAG = "LCLOG_FeaturePopuWindow"
    private lateinit var mContext: Activity
    private lateinit var mMenuView: View
    private lateinit var rcProvince: RecyclerView
    private lateinit var rcCity: RecyclerView
    private lateinit var bttClear: Button
    private lateinit var bttSure: Button
    private lateinit var adapterProvince: DistrictAdapter
    private lateinit var adapterCity: DistrictAdapter
    private var listProvince = arrayListOf<DistrictModel>()
    private var listCity = arrayListOf<DistrictModel>()
    private lateinit var callBackListener: LCInterface.LcCallBack

    private var currentCode = ""//当前地区代码
    private var currentDistrict = ""//当前地区

    fun init(context: Activity) {
        this.mContext = context
        findView()
        initPopu()
        requestProvince()
    }

    //初始化
    private fun initPopu() {
        this.contentView = mMenuView
        this.width = LayoutParams.MATCH_PARENT
        this.height = LayoutParams.MATCH_PARENT
        //设置SelectPicPopupWindow弹出窗体可点击
        this.isFocusable = false
        this.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        this.isOutsideTouchable = false
        this.isTouchable = true
        this.isClippingEnabled = false ///覆盖状态栏，
        setTouchInterceptor { view, motionEvent -> false }
    }

    @SuppressLint("NewApi")
    private fun findView() {
        val inflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        mMenuView = inflater.inflate(R.layout.view_district_popuwindow, null)
        bttClear = mMenuView.findViewById(R.id.view_district_clear_btt)
        bttSure = mMenuView.findViewById(R.id.view_district_sure_btt)
        rcProvince = mMenuView.findViewById(R.id.view_district_province)
        rcCity = mMenuView.findViewById(R.id.view_district_city)

        bttClear.setOnClickListener {
            callBackListener.callBack("")
            clearChecked()
            dismiss()
        }
        bttSure.setOnClickListener {
            callBackListener.callBack(currentDistrict)
            dismiss()
        }

//        for (index in 0 until 10) {
//            val item = TypeModel().apply { name = "$index 山东" }
//            listProvince.add(item)
//        }
//
//        for (index in 0 until 10) {
//            val item = TypeModel().apply { name = "$index 济南" }
//            listCity.add(item)
//        }

        rcProvince.layoutManager = LinearLayoutManager(mContext)
        adapterProvince = DistrictAdapter(mContext, 0, listProvince, object : LCInterface.LcCallBack {
            override fun callBack(vararg args: Any?) {
                val posiiton = args[0] as Int
                currentCode = listProvince[posiiton].code
                currentDistrict = listProvince[posiiton].name
                requestCity(listProvince[posiiton].code)
            }
        })
        rcProvince.adapter = adapterProvince

        rcCity.layoutManager = LinearLayoutManager(mContext)
        adapterCity = DistrictAdapter(mContext, 1, listCity, object : LCInterface.LcCallBack {
            override fun callBack(vararg args: Any?) {
                val posiiton = args[0] as Int
//                currentCode = listCity[posiiton].code
                if (!isInCity()) {
                    currentDistrict = listCity[posiiton].name
                }
            }
        })
        rcCity.adapter = adapterCity

    }

    private fun isInCity(): Boolean {
        val citys = arrayListOf("11", "12", "31", "50")
        return citys.contains(currentCode)
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            //地形
//            R.id.view_maplayer_terrain -> {
//                callBackListener.callBack("layout_terrain")
//            }
        }
    }

    override fun showAtLocation(parent: View?, gravity: Int, x: Int, y: Int) {
//        setBackgroundAlpha(0.8f)
        super.showAtLocation(parent, gravity, x, y)
    }

    /**
     *  @time 2024/7/8  16:39
     *  @author Im_jingwei
     *  @desc 事件回调接口
     */
    fun setPopuOnclickListener(listener: LCInterface.LcCallBack) {
        this.callBackListener = listener
    }

    /**
     *  @time 2025/1/22  11:22
     *  @author Im_jingwei
     *  @desc 请求省份数据
     */
    fun requestProvince() {
        val httpUtil = OkHttpUtil()
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_DISTRICT_PROVINCES
        httpUtil.httpRequestGet(url, token, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(mContext, "请求数据失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                val jsonArray = JSONArray(response)
                listProvince.clear()
                for (index: Int in 0 until jsonArray.length()) {
                    val jsonObject = jsonArray.getJSONObject(index)
                    val mode = DistrictModel().apply { getModelInfo(jsonObject) }
                    listProvince.add(mode)
                }
                mContext.runOnUiThread { adapterProvince.notifyDataSetChanged() }
            }
        })
    }

    /**
     *  @time 2025/6/11  11:35
     *  @desc 城市
     */
    fun requestCity(code: String) {
        val httpUtil = OkHttpUtil()
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_DISTRICT_CITY + "?provinceCode=$code"
        httpUtil.httpRequestGet(url, token, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                LCBaseUtil.showToast(mContext, "请求数据失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                val jsonArray = JSONArray(response)
                listCity.clear()
                for (index: Int in 0 until jsonArray.length()) {
                    val jsonObject = jsonArray.getJSONObject(index)
                    val mode = DistrictModel().apply { getModelInfo(jsonObject) }
                    listCity.add(mode)
                }
                mContext.runOnUiThread { adapterCity.notifyDataSetChanged() }
            }
        })
    }

    private fun clearChecked() {
        for (item in listProvince) {
            if (item.isChecked) {
                item.isChecked = false
            }
        }
        adapterProvince.notifyDataSetChanged()
        for (item in listCity) {
            if (item.isChecked) {
                item.isChecked = false
            }
        }
        adapterCity.notifyDataSetChanged()
    }

    /**
     *  @time 2024/7/8  16:39
     *  @author Im_jingwei
     *  @desc 销毁
     */
    override fun dismiss() {
        //关闭软键盘
        setBackgroundAlpha(1.0f)
        super.dismiss()
    }

    //设置窗口颜色
    private fun setBackgroundAlpha(bgAlpha: Float) {
        val lp = (mContext as Activity).window.attributes
        (mContext as Activity).window.setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND, WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        lp.alpha = bgAlpha //0.0-1.0
        (mContext as Activity).window.attributes = lp
    }

}